<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class OrderRefund extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->field("order.*")
            ->field("(select name from user where id = order.user_id) as user_name")
            ->field("(select name from user where id = order.car_old_user_id) as old_user_name")
            ->where("refund_status",">",0)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    //审核 通过
    public function shenhe()
    {

        $id = input("id");
        if (empty($id)){
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $detail = Db::name("order")->where("id",$id)->where("refund_status",1)->find();
        if (empty($detail)) {
            $this->error("退款订单不存在");
        }

        Db::startTrans();
        try {
           $result =  Db::name("order")->where("id",$id)->update([
                "refund_auditing_time"=>time(),
                "refund_status"=>3,
                "status"=>4,
                "refund_reject_voucher"=>""
            ]);
           if (!$result) {
               $this->error("订单异常，请稍后再试");
           }

           $user = Db::name("user")->where("id",$detail["user_id"])->find();
           if ($user["margin"] < $detail["price"]) {
               Db::rollback();
               $this->error("用户保证金账户余额不足");
           }

           $result = Db::name("user")->where("id",$detail["user_id"])->dec("margin",$detail["price"])->update();
           if (!$result) {

               Db::rollback();
               $this->error("用户保证金账户扣款失败");
           }


           // --------       这里执行退款接口       -----------
           if (true) {

               if ($detail["refund_reason"] == "交易完成") {
                  $trade_status = 3; //修改车源状态为 已售
               } else {
                   $trade_status = 1; //修改车源状态为 在售
               }
               //修改车源状态
               Db::name("car_old")->where("id",$detail["car_old_id"])->update([
                   "trade_status"=>$trade_status,
               ]);

               Db::commit();
               $this->success("退款成功");
           } else {
               $this->error("退款接口异常");
               Db::rollback();
           }



        }catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error("服务超时请稍后再试");
        }

    }


    //审核 驳回
    public function bohui()
    {

        $id = input("id");
        $info = input("rejection_info");
        if (empty($id)&&empty($info)){
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $res = Db::name("order")->where("id",$id)->update([
            "refund_auditing_time"=>time(),
            "refund_status"=>4,
            "refund_reject_voucher"=>$info
        ]);

        if ($res) {
            $this->success("已驳回");
        } else {
            $this->error("驳回失败，请稍后再试");
        }

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
